//
//  CarImagesCell.swift
//  Automobile
//
//  Created by erkebulan elzhan on 8/12/20.
//  Copyright © 2020 erkebulan elzhan. All rights reserved.
//

import UIKit
import SnapKit


// MARK: - Base

final class CarHeaderCell: UITableViewCell, ConfigurableCell {
    
    // MARK: - Outlets
    
    private lazy var mainStack: UIStackView = {
        let stack = UIStackView()
        stack.axis = .vertical
        stack.alignment = .fill
        stack.distribution = .equalSpacing
        return stack
    }()
    
    private lazy var imagesScrollView: UIScrollView = {
        let scroll = UIScrollView()
        scroll.showsHorizontalScrollIndicator = false
        scroll.backgroundColor = .rgb(238,241,246)
        scroll.isPagingEnabled = true
        return scroll
    }()
    
    private lazy var imagesStack: UIStackView = {
        let stack = UIStackView()
        stack.axis = .horizontal
        stack.alignment = .leading
        stack.distribution = .equalSpacing
        stack.spacing = 12
        return stack
    }()
    
    private lazy var headerView: UIView = {
        let view = UIView ()
        view.backgroundColor = .white
        return view
    }()
    
    private lazy var titleLbl: UILabel = {
        let lbl = UILabel()
        lbl.font = UIFont.systemFont(ofSize: 17, weight: .medium)
        lbl.textColor = .black
        lbl.numberOfLines = 0
        lbl.text = "Название"
        return lbl
    }()
    private lazy var priceLbl: UILabel = {
        let lbl = UILabel()
        lbl.font = UIFont.systemFont(ofSize: 24, weight: .bold)
        lbl.textColor = .black
        lbl.text = "0"
        lbl.sizeToFit()
        lbl.numberOfLines = 2
        return lbl
    }()
    
    lazy private var footerView: UIView = {
        let view = UIView ()
        view.backgroundColor = .white
        return view
    }()
    
    lazy var dateLbl: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 13, weight: .medium)
        label.textColor = .greyColor
        label.text = "час назад"
        label.textAlignment = .left
        return label
    }()
    
    lazy var visCountView: UIStackView = {
        let view = UIStackView()
        view.axis = .horizontal
        view.spacing = 8
        view.alignment = .leading
        view.distribution = .equalSpacing
        
        // vis icon
        let icon = UIImageView(frame: CGRect(x: 0, y: 0, width: 16, height: 10.5))
        icon.tag = 1
        icon.image = UIImage(named: "eye")
        
        // vis count label
        let label = UILabel(frame: CGRect(x: 0, y: 0, width: 0, height: 24))
        label.tag = 2
        label.font = UIFont.systemFont(ofSize: 13, weight: .medium)
        label.textColor = .greyColor
        label.text = "24 544"
        label.sizeToFit()
        
        view.addArrangedSubview(icon)
        view.addArrangedSubview(label)
        
        icon.snp.makeConstraints { (make) in
            make.width.equalTo(18)
            make.height.equalTo(16)
        }
        
        return view
    }()
    
    private lazy var marketingIconsStack: UIStackView = {
        let stack = UIStackView ()
        stack.axis = .horizontal
        stack.alignment = .fill
        stack.distribution = .fillEqually
        stack.spacing = 16
        return stack
    }()
    
    private lazy var cityNameLbl: UILabel = {
        let label = UILabel()
        label.textAlignment = .left
        label.font = UIFont.systemFont(ofSize: 15, weight: .medium)
        label.sizeToFit()
        label.textColor = .greyColor
        return label
    }()
    
    private lazy var likeBtn: UIButton = {
        let button = UIButton()
        button.setImage(UIImage(named: "like"), for: .normal)
        return button
    }()
    
    private lazy var separatorView = CellSeparator()
    
    private lazy var galleryViewer = GalleryViewer()
    
    // MARK: - Props

    public var isPreview = false
    
    private var data: MainViewModel.CarHeader!
    
    // MARK: - Init
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.setUI(isPreview: reuseIdentifier == "postPreview" || reuseIdentifier == "topPostPreview")
        self.isUserInteractionEnabled = true
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func configure(data object: MainViewModel.CarHeader?, index: Int) {
        self.data = object!
        self.handleImages()
        self.handleHeader()
        self.handleIcons()
    }
    
    func returnData() -> MainViewModel.CarHeader? {
        return nil
    }
}


// MARK: - Methods

extension CarHeaderCell {
    
    @objc private func onImageClick (sender: GestureWithTag) {
        galleryViewer = GalleryViewer()
        let pageIndex = imagesScrollView.currentPage
        
        UIApplication.shared.keyWindow!.addSubview(galleryViewer)
        UIApplication.shared.keyWindow!.bringSubviewToFront(galleryViewer)
        
        galleryViewer.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        galleryViewer.backBtn.addTarget(self, action: #selector(closeGallery), for: .touchUpInside)
        
        self.showGallery(galleryViewer: galleryViewer)
        
        galleryViewer.setProps(images: (data.images ?? []).map { $0.image_thumbnail }, index: pageIndex)
    }
    
    @objc private func closeGallery () {
        UIView.animate(withDuration: 0.3, animations: {
            self.galleryViewer.transform = CGAffineTransform(translationX: 0, y: UIScreen.main.bounds.height)
        }, completion: { _ in
            self.galleryViewer.transform = .identity
            self.galleryViewer.removeFromSuperview()
        })
    }
    
    private func showGallery (galleryViewer: GalleryViewer) {
        galleryViewer.transform = CGAffineTransform(translationX: 0, y: UIScreen.main.bounds.height)
        UIView.animate(withDuration: 0.3, animations: {
            galleryViewer.transform = .identity
        })
    }
}

// MARK: - UI

extension CarHeaderCell {
    
    private func setUI (isPreview: Bool = false) {
        self.contentView.addSubview(mainStack)
        mainStack.addArrangedSubview(headerView)
        headerView.addSubview(titleLbl)
        headerView.addSubview(marketingIconsStack)
        headerView.addSubview(priceLbl)
        headerView.addSubview(footerView)
        let _ = Divider(parent: self.footerView)
        footerView.addSubview(dateLbl)
        footerView.addSubview(visCountView)
        self.handleConstraints(isPreview: isPreview)
        
        let tap = GestureWithTag(target: self, action: #selector(onImageClick(sender:)))
        tap.tag = 100
        self.imagesStack.addGestureRecognizer(tap)
    }
    
    private func handleImages () {
        
        let isLocalImages = self.data.localImgs.count != 0
        let images: [Any] = isLocalImages ? self.data.localImgs : (self.data.images ?? [])
        
        _ = self.imagesStack.arrangedSubviews.map {
            self.imagesStack.removeArrangedSubview($0)
            $0.removeFromSuperview()
        }
        
        if images.count != 0 {
            
            for image in images {
                var imageView: UIImageView!
                
                if isLocalImages {
                    imageView = self.createCarImage(image: image as? UIImage)
                } else {
                    imageView = self.createCarImage(url: URL(string: (image as! PostImage).image_thumbnail))
                }
                
                self.imagesStack.addArrangedSubview(imageView)
                
                imageView.snp.makeConstraints { (make) in
                    make.top.bottom.equalToSuperview().inset(12)
                    make.width.equalTo(UIScreen.main.bounds.width - (images.count == 1 ? 32 : 48))
                    make.height.equalTo(192)
                }
            }
            
            imagesScrollView.addSubview(imagesStack)
            
            imagesStack.snp.makeConstraints { (make) in
                make.leading.trailing.equalToSuperview().inset(16)
                make.top.bottom.equalToSuperview()
            }
            
            self.mainStack.insertArrangedSubview(imagesScrollView, at: 0)
            
            imagesScrollView.snp.makeConstraints { (make) in
                make.leading.trailing.equalToSuperview()
                make.height.equalTo(216)
                make.top.equalToSuperview()
            }
        }
    }

    private func handleIcons () {
        
        _ = marketingIconsStack.arrangedSubviews.map {
            marketingIconsStack.removeArrangedSubview($0)
            $0.removeFromSuperview()
        }
        
        if data.postMarketing?.isTop ?? false {
            let icon = self.createIcon(iconName: "top")
            marketingIconsStack.addArrangedSubview(icon)
        }
        
        if data.postMarketing?.special ?? false {
            let icon = self.createIcon(iconName: "safe")
            marketingIconsStack.addArrangedSubview(icon)
        }
        
        if data.postMarketing?.colored ?? false {
            let icon = self.createIcon(iconName: "paint")
            marketingIconsStack.addArrangedSubview(icon)
        }
    }
    
    private func handleHeader () {
        self.titleLbl.text = data.titleString
        (self.visCountView.viewWithTag(2) as! UILabel).text = data.visCount
        self.priceLbl.text = data.price
        self.dateLbl.text = data.date
    }

    private func createIcon (iconName: String) -> UIImageView {
        let imageView = UIImageView()
        imageView.image = UIImage(named: iconName)
        imageView.contentMode = .scaleAspectFit
        imageView.snp.makeConstraints { (make) in
            make.width.height.equalTo(16)
        }
        return imageView
    }
    
    private func createCarImage (url: URL?=nil, image: UIImage?=nil) -> UIImageView {
        
        let imageView = UIImageView()
        
        if let _image = image {
            imageView.image = _image
        } else if let _url = url {
            imageView.sd_setImage(with: _url)
        }
        
        let tap = GestureWithTag(target: self, action: #selector(onImageClick(sender:)))
        imageView.addGestureRecognizer(tap)
        
        imageView.contentMode = .scaleAspectFill
        imageView.layer.cornerRadius = 7
        imageView.clipsToBounds = true
        
        return imageView
    }

    private func handleConstraints (isPreview: Bool) {
        
        if (!isPreview) {
            self.contentView.addSubview(separatorView)
            separatorView.snp.makeConstraints { (make) in
                make.leading.trailing.bottom.equalToSuperview()
            }
            mainStack.snp.makeConstraints { (make) in
                make.top.equalToSuperview()
            }
        } else {
            self.contentView.addSubview(cityNameLbl)
            self.contentView.addSubview(likeBtn)
            
            mainStack.snp.makeConstraints { (make) in
                make.top.equalTo(cityNameLbl.snp.bottom).offset(7)
            }
            
            likeBtn.snp.makeConstraints { (make) in
                make.width.height.equalTo(16)
                make.top.equalToSuperview().inset(20)
                make.trailing.equalToSuperview().inset(16)
            }
            
            cityNameLbl.snp.makeConstraints { (make) in
                make.leading.equalToSuperview().offset(16)
                make.trailing.equalTo(likeBtn.snp.leading).offset(-8)
                make.top.equalToSuperview().offset(17)
                make.height.equalTo(24)
            }
        }
        
        mainStack.snp.makeConstraints { (make) in
            make.leading.trailing.equalToSuperview()
            make.bottom.equalTo(isPreview ? contentView : separatorView.snp.top)
        }
                
        titleLbl.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(isPreview ? 8 : 20)
            make.leading.trailing.equalToSuperview().inset(16)
        }
        
        marketingIconsStack.snp.makeConstraints { (make) in
            make.top.equalTo(titleLbl.snp.bottom).offset(15)
            make.trailing.equalToSuperview().inset(16)
            make.height.equalTo(16)
        }
        
        priceLbl.snp.makeConstraints { (make) in
            make.leading.equalToSuperview().inset(16)
            make.top.equalTo(titleLbl.snp.bottom).offset(16)
            make.trailing.equalTo(marketingIconsStack.snp.leading).offset(-8)
        }
        
        footerView.snp.makeConstraints { (make) in
            make.leading.trailing.equalToSuperview().inset(16)
            make.height.equalTo(48)
            make.top.equalTo(priceLbl.snp.bottom).offset(12)
            make.bottom.equalToSuperview().inset(4)
        }
        
        dateLbl.snp.makeConstraints { (make) in
            make.centerY.leading.equalToSuperview()
            make.height.equalTo(24)
        }
        
        visCountView.snp.makeConstraints { (make) in
            make.leading.equalTo(dateLbl.snp.trailing).offset(33)
            make.height.equalTo(24)
            make.centerY.equalToSuperview().offset(4)
        }
    }
}


// MARK: - UI Helpers

extension CarHeaderCell {
    
    public func updateTheme (isDark: Bool, isPreview: Bool, cityName: String?) {
        contentView.backgroundColor = isDark ? .darkBlueColor : .white
        self.backgroundColor = isDark ? .darkBlueColor : .white
        
        imagesScrollView.backgroundColor = isDark ? .darkBlueColor : isPreview ?.white :  .rgb(238,241,246)
        headerView.backgroundColor = isDark ? .darkBlueColor : .white
        footerView.backgroundColor = isDark ? .darkBlueColor : .white
        titleLbl.textColor = isDark ? .white : .black
        priceLbl.textColor = isDark ? .white : .black
        self.cityNameLbl.text = cityName
    }
    
    public func updateFullScreen () {
        footerView.removeFromSuperview()
        separatorView.removeFromSuperview()
        imagesScrollView.backgroundColor = .white
        priceLbl.snp.makeConstraints { (make) in
            make.bottom.equalToSuperview().inset(16)
        }
        mainStack.snp.makeConstraints { (make) in
            make.bottom.equalToSuperview()
        }
    }
}
